#! /bin/python3

import logging
import time
from datetime import datetime, timedelta
import urllib.parse
import argparse
from localsvc.config import LocalSvcConfig
from localsvc.discovery import nacos
from localsvc import beanfactory


def print_hint():
    print("如果服务无法访问，去nacos控制台看服务是不是某天被手动下线了")


def create_discovery_server(container: beanfactory.ApplicationContainer, server, url):
    '''Factory method to create discovery server
    '''
    if server == 'nacos':
        sh = container.get_scheduler()

        def scheduler(runner, timeout):
            sh.add_job(runner, 'date', run_date=datetime.now() +
                       timedelta(milliseconds=timeout))

        r = urllib.parse.urlparse(url)
        return nacos.NacosDiscovery(
            r.hostname,
            r.port,
            scheduler,
            container.get_nginx_proxy())
    raise Exception(f'Unsupported server type: %s', server)


if __name__ == "__main__":
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(name)s - %(message)s')
    logging.basicConfig(
        level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s - %(message)s')
    logging.getLogger('apscheduler').setLevel(logging.WARN)

    logger = logging.getLogger("main")

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--discovery-server", help="set Server Discovery service type", default="nacos")
    parser.add_argument(
        "--discovery-url", help="set Server Discovery service url", default="http://localhost:8848")
    parser.add_argument('config', help='Config file path')
    parser.add_argument(
        'rest', help='Discovery server specified options, for example "--nacos-namespace localsvc", "namespace=localsvc" will be used for registering', nargs=argparse.REMAINDER)
    args = parser.parse_args()

    server_type = args.discovery_server
    # body length of '--nacos-xxx': length of 'xxx
    l = 2 + len(server_type) + 1
    discovery_server_ops = dict(zip(map(lambda x: x[l:], filter(
        lambda x: x.startswith(f'--{server_type}'), args.rest[::2])), args.rest[1::2]))

    appconfig = LocalSvcConfig(args.config)

    with beanfactory.open_container() as app_container:
        # init discovery server
        discovery_server = create_discovery_server(
            app_container, server_type, args.discovery_url)

        # register all services
        for p in appconfig.list_projects():
            logger.debug('Registering service: %s %s', p.name, p.url)
            # TODO namespace groupName arguments
            discovery_server.register(p.name, p.url, **discovery_server_ops)
        app_container.after_setup()

        logger.info("Running...")
        print_hint()
        try:
            while True:
                time.sleep(60)
        except KeyboardInterrupt:
            logger.info("Exiting...")
